package com.yllt4cloud.shangmi.biz.control;

import cn.hutool.core.util.ObjectUtil;
import com.yllt4cloud.base.api.entity.SheBei;
import com.yllt4cloud.base.api.feign.RemoteSheBeiService;
import com.yllt4cloud.common.core.constant.CacheConstants;
import com.yllt4cloud.common.core.constant.SecurityConstants;
import com.yllt4cloud.common.core.constant.SystemConfigConstants;
import com.yllt4cloud.common.core.util.ResultResp;
import com.yllt4cloud.common.ddbase.constant.ErrorCode;
import com.yllt4cloud.common.ddbase.constant.GlobalConstants;
import com.yllt4cloud.common.ddbase.param.jsonparam.RequestJsonParam;
import com.yllt4cloud.shangmi.api.dto.ShangMiRoomDto;
import com.yllt4cloud.shangmi.api.entity.ShangMiRoom;
import com.yllt4cloud.shangmi.biz.service.IShangMiRoomService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("room")
public class ShangMiRoomController {

    @Autowired
    RemoteSheBeiService remoteSheBeiService;

    @Autowired
    IShangMiRoomService shangMiRoomService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(value = "query")
    public ResultResp<?> query(@RequestJsonParam("data") ShangMiRoomDto param) {
        List<ShangMiRoom> roomList = new ArrayList<>();
        if (StringUtils.isNotBlank(param.getSheBeiId())) {
            ResultResp<SheBei> resultResp=remoteSheBeiService.getSheBeiById(param.getSheBeiId(), SecurityConstants.FROM_IN);
            SheBei sheBei=resultResp.getResult();
            if(ObjectUtil.isNull(sheBei)){
                return ResultResp.fail("当前设备无法通过设备验证", ErrorCode.DATA_DOESNOT_EXIST);
            }
            if (GlobalConstants.TRUE.equals(sheBei.getCanShanMiQuanXianFlag())) {
                redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(String.class));
                String  sysTime= (String) redisTemplate.opsForHash().get(CacheConstants.SYSTEMCONFIG_KEY, SystemConfigConstants.SYSTEM_TIME);
                try {
                    param.setWorkDate(new SimpleDateFormat("yyyy-MM-dd").parse(sysTime));
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                param.setOrderBy("t1.orderNum asc, t1.Id asc");
                roomList = shangMiRoomService.queryRoomList(param);
            }

        }
        return ResultResp.success(roomList);
    }

}
